﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.AccessControl;
using System.Threading;
using System.Threading.Tasks;

using Utils;

namespace MicroCenter.Services
{


    public class SystemctlService
    {
        private const string _serviceName = "MicroCenter";

        private const string serviceFull = "/etc/systemd/system/micro-center.service";
        public static bool RunCommand(string[] args)
        {
            if (args != null && args.Length > 0 && ProcessHelper.IsLinux())
            {
                switch (args[0])
                {
                    case "stop":
                        Stop();
                        break;
                    case "start":
                        Start();
                        break;
                    case "restart":
                        ReStart();
                        break;
                    case "enable":
                        Enable();
                        break;
                    case "disable":
                        Disable();
                        break;
                    default:
                        return false;
                }
                return true;
            }

            return false;
        }


        private static void Start()
        {
            var pc = Process.GetCurrentProcess();
            if (Process.GetProcessesByName(_serviceName).Any(p => pc.Id != p.Id))
            {
                Console.WriteLine("服务已启动");
                return;
            }
            ProcessHelper.RunCmd($"nohup  ./{_serviceName} > log.out 2>&1 & ", $"{Environment.CurrentDirectory}/").Start().GetAwaiter().GetResult();
        }

        private static void ReStart()
        {
            Stop();
            Thread.Sleep(1000);
            Start();
        }

        private static void Stop()
        {
            if (File.Exists(serviceFull))
            {
                ProcessHelper.RunCmd($"systemctl stop micro-center").Start(Console.WriteLine).GetAwaiter().GetResult();
            }

            var pc = Process.GetCurrentProcess();
            Process.GetProcessesByName(_serviceName).ForEach(p =>
            {
                if (pc.Id == p.Id) return;
                p.Kill();
            });

        }

        private static void Enable()
        {
            if (!File.Exists(serviceFull))
            {
                File.WriteAllText(serviceFull, GetServiceSH(Environment.CurrentDirectory));
            }
            ProcessHelper.RunCmd($"systemctl daemon-reload && systemctl enable micro-center").Start(Console.WriteLine).GetAwaiter().GetResult();
        }

        private static void Disable()
        {
            if (File.Exists(serviceFull))
            {
                File.Delete(serviceFull);
            }
            ProcessHelper.RunCmd($"systemctl disable micro-center").Start(Console.WriteLine).GetAwaiter().GetResult();
        }

        private static string GetServiceSH(string dir) => $@"[Unit]
Description=microCenter
After=network.target

[Service]
Type=forking
Environment=""PATH=/sbin:/usr/sbin:/bin:/usr/bin""
Environment=""DOTNET_BUNDLE_EXTRACT_BASE_DIR=/root/.net""
WorkingDirectory={dir}
ExecStart={dir}/{_serviceName} start
PrivateTmp=true
Restart=on-failure

[Install]
WantedBy=multi-user.target";

    }
}
